﻿namespace EasyToolkit.BindingTemplates.Views
{
    using System;
    using System.Collections.Generic;
    using EasyToolkit.BindingTemplates.Definitions;
    using EasyToolkit.BindingTemplates.SortAndFilter;

    public abstract class RootTemplateView : TemplateView, IRootTemplateView
    {
        #region attributes and properties
        private Dictionary<ITemplateDefinition, ISortAndFilter> sortsAndFilters;
        public Dictionary<ITemplateDefinition, ISortAndFilter> SortsAndFilters
        {
            get { return sortsAndFilters; }
            set
            {
                sortsAndFilters = value;
                if (sortsAndFilters != null)
                {
                    ISortAndFilter sortAndFilter = null;
                    sortsAndFilters.TryGetValue(TemplateDefinition, out sortAndFilter);
                    SortAndFilter = sortAndFilter;
                }
            }
        }
        #endregion

        #region IRootTemplateView Members
        abstract public void Render();
        abstract public void RenderDataOnly();

        public void ApplyFilter()
        { }

        public RootTemplateView(ITemplateDefinition templateDefinition)
                               : base(null, templateDefinition, null)
        {
            RootParent = this;
            BindingTemplateManager.Instance.AddView(this);
        }

        virtual public void Clear()
        {
            SetDataSource(null);    
        }

        public object GetDataSource()
        {
            return BindingContext == null ? null : BindingContext.DataSource;
        }

        virtual public void SetDataSource(object dataSource)
        {
            lock (syncRoot)
            {
                try
                {
                    if (BindingContext != null)
                        BindingContext.Dispose();
                    if (dataSource != null)
                        BindingContext = new Context.BindingContext(null, this.TemplateDefinition, dataSource, SortsAndFilters, -1);
                }
                catch (Exception ex)
                {
                    string message = string.Format("Binding template '{0}', 'SetDataSource' failed. {1}", TemplateDefinition.Name, ex.Message);
                    throw new EasyToolkitException(message);
                }
            }
        }
        #endregion
    }
}
